﻿using BotDetector.Core;
using BotDetector.Core.Utilities;
using BotDetector.Web.Models;
using System.IO;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace BotDetector.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index([Bind(Include = "Text")] Message message)
        {
            if (ModelState.IsValid)
            {
                double rez = DetectorCreator.Detector.Classify(message.Text);
                message.BotProbability = rez;
            }
            
            return View(message);
        }

        public ActionResult Train()
        {
            SetTrainerStatusMessage();
            return View();
        }

        public async Task<ActionResult> Retrain()
        {
            await Task.Run(() => DetectorTrainer.Train());

            SetTrainerStatusMessage();
            return View("Train");
        }

        [HttpPost]
        public ActionResult AddBotFiles(HttpPostedFileBase[] files)
        {
            AddTrainFiles(files, Constants.BotQueuePath);

            SetTrainerStatusMessage();
            return View("Train");
        }

        [HttpPost]
        public ActionResult AddNonbotFiles(HttpPostedFileBase[] files)
        {
            AddTrainFiles(files, Constants.NonbotQueuePath);

            SetTrainerStatusMessage();
            return View("Train");
        }

        private void SetTrainerStatusMessage()
        {
            if (DetectorTrainer.Status == TrainerStatus.UnderTraining)
            {
                ViewBag.RetrainMessage = Resources.ViewResources.RetrainWarningMessage;
            }
            else
            {
                ViewBag.RetrainMessage = Resources.ViewResources.RetrainSuccessfulMessage;
            }
        }
        private void AddTrainFiles(HttpPostedFileBase[] files, string path)
        {
            string basePath = Path.GetDirectoryName(Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory));
            try
            {
                foreach (HttpPostedFileBase file in files)
                {
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    file.SaveAs(basePath + path + "\\" + filename);
                }
                ViewBag.MessageBot = Resources.ViewResources.FileUploadedSuccessfulMessage;
            }
            catch
            {
                ViewBag.MessageBot = Resources.ViewResources.FileNotUploadedMessage;
            }
        }
    }
}